package org.lalib.controller.action;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.lalib.acquire.IControllerAction;
import org.lalib.controller.form.COrderReportForm;
import org.lalib.controller.form.COrderReportForm.OrderReportBean;
import org.lalib.controller.service.CFoodService;
import org.lalib.controller.service.CHistoricalValueService;
import org.lalib.controller.service.COrderService;
import org.lalib.entity.object.EFood;
import org.lalib.entity.object.EHistoricalValue;
import org.lalib.entity.object.EOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Scope("request")
@Controller("cOrderReportAction")
public class COrderReportAction implements IControllerAction {

	private static final long serialVersionUID = 1L;

	@Autowired
	COrderReportForm cOrderReportForm;

	@Autowired
	COrderService cOrderService;

	@Autowired
	CFoodService cFoodService;

	@Autowired
	CHistoricalValueService cHistoricalValueService;

	public String init() {
		return "orderReport";
	}

	public void generateTable() {
		Date startDate = cOrderReportForm.getStartDate();
		Date endDate = cOrderReportForm.getEndDate();
		List<EOrder> orders = cOrderService.getAllTakenOrders(startDate, endDate);

		List<OrderReportBean> orderBeans = new ArrayList<>();
		for (EOrder order : orders)
			orderBeans.add(cOrderReportForm.new OrderReportBean(order, showPrice(order.geteFood())));
		cOrderReportForm.setOrderBeans(orderBeans);
		cOrderReportForm.setOrders(orders);
	}

	@SuppressWarnings("rawtypes")
	public Double showPrice(EFood food) {
		food = (EFood) cFoodService.getFoodById(food.getId());
		EHistoricalValue value = cHistoricalValueService.getValue(food, "fiyat");
		Double price = (double) 0;
		if (value != null && value.getCore() != null)
			price = ((BigDecimal) value.getCore()).doubleValue();
		return price;
	}
}